package resource

import (
	"encoding/json"
	"fcs-api/src/app/model"
	"fcs-api/src/app/utils"
	"time"

	"k8s.io/apimachinery/pkg/util/wait"
)

var ecsSchedulePeriod = time.Minute * 20
var ecsStopCh chan struct{}

type EcsListResult struct {
	Code    int
	Message string
	Data    *EcsList
}

type EcsList struct {
	TotalCount int `json:"totalCount"`
	Servers    []*EcsInfo
}

type EcsInfo struct {
	Id     string
	Name   string
	Status string
	Flavor *FlavorInfo
	Nics   []*AddrInfo
	Image  *ImageInfo
}

type AddrInfo struct {
	FixedIp string `json:"fixedIp"`
	PortMac string `json:"portMac"`
}

type FlavorInfo struct {
	Ram   float64 // 内存G
	Vcpus int64   // cpu核数
}

type ImageInfo struct {
	System string // 系统版本，例如centos6.4
}

func MonitoringEcs() {
	ecsStopCh = make(chan struct{})
	go wait.Until(getProxyEcs, ecsSchedulePeriod, ecsStopCh)
}

func getProxyEcs() {
	token := utils.GetAdminToken()
	if token != "" {
		ecsListUrl := "ecs/v1.1/servers/1/100?fast=true&searchField=name&searchValue=fcs-vpc-proxy"
		url := model.Base.EcsHost + ecsListUrl
		// 获取ecs列表中名为fcs-vpc-proxy的集群
		body, err := utils.HttpReq(url, "bearer "+token, "GET", nil, nil)
		if err != nil {
			logger.Error("getProxyEcs: Query ecs server list error %s", err.Error())
			return
		}
		ecsListResult := new(EcsListResult)
		err = json.Unmarshal(body, ecsListResult)
		if err != nil {
			logger.Error("getProxyEcs: Unmarshal ecs server list response body error %s, body is %s",
				err.Error(), string(body))
			return
		}
		if ecsListResult.Data.TotalCount == 0 {
			logger.Info("getProxyEcs: no fcs-proxy ecs detect")
			return
		}
		proxyServers, err := model.GetAllServer()
		if err != nil {
			logger.Error("getProxyEcs: Get proxy servers from db error %s", err.Error())
			return
		}
		proxyIdSet := getServerIdSet(proxyServers)
		for _, server := range ecsListResult.Data.Servers {
			exists := proxyIdSet[server.Id]
			// 如果数据库中没有这个虚机，那么加入到库中
			if !exists {
				if len(server.Nics) != 0 {
					proxyServer := &model.ProxyServer{
						Id:         server.Id,
						ServerIp:   server.Nics[0].FixedIp,
						RootP6d:    "",
						ServerName: server.Name,
						Mac:        server.Nics[0].PortMac,
					}
					if server.Flavor != nil {
						proxyServer.Ram = int(server.Flavor.Ram)
						proxyServer.Cpu = int(server.Flavor.Vcpus)
					}
					if server.Image != nil {
						proxyServer.System = server.Image.System
					}
					_, err := model.CreateServer(proxyServer)
					if err != nil {
						logger.Error("getProxyEcs: Create proxy server error %s", err.Error())
					}
				}
			}
		}
	}
}

func getServerIdSet(servers []*model.ProxyServer) map[string]bool {
	idSet := make(map[string]bool)
	for _, server := range servers {
		idSet[server.Id] = true
	}
	return idSet
}
